"""
Routing configuration management
"""
from typing import Dict, List, Any, Optional
import json
from .base import RoutingRule, MessageRouter
from .conditions import ConditionalRouter, CommonConditions
from .broadcast import BroadcastRouter, CommonBroadcastConditions

class RoutingConfig:
    """路由配置管理器"""
    
    def __init__(self):
        self.base_routes: Dict[str, str] = {}  # 基本路由规则
        self.default_order: List[str] = []     # 默认路由顺序
        self.conditional_routes: List[Dict] = []  # 条件路由规则
        self.broadcast_patterns: List[Dict] = []  # 广播模式
        
    def set_base_routes(self, router: MessageRouter) -> None:
        """
        从MessageRouter更新基本路由规则
        Args:
            router: 消息路由器实例
        """
        self.base_routes = router.base_rule.routes.copy()
        self.default_order = router.base_rule.default_order.copy()
        
    def set_conditional_routes(self, router: ConditionalRouter) -> None:
        """
        从ConditionalRouter更新条件路由规则
        Args:
            router: 条件路由器实例
        """
        self.conditional_routes = []
        for source, conditions in router.conditions.items():
            for condition in conditions:
                self.conditional_routes.append({
                    "source": source,
                    "target": condition.target,
                    "description": condition.description,
                    "type": "custom"  # 自定义条件无法序列化函数
                })
                
    def set_broadcast_patterns(self, router: BroadcastRouter) -> None:
        """
        从BroadcastRouter更新广播模式
        Args:
            router: 广播路由器实例
        """
        self.broadcast_patterns = []
        for source, patterns in router.patterns.items():
            for pattern in patterns:
                self.broadcast_patterns.append({
                    "source": source,
                    "targets": pattern.get_targets(),
                    "description": pattern.description,
                    "has_condition": pattern.condition is not None
                })
                
    def to_dict(self) -> Dict:
        """
        将配置转换为字典格式
        Returns:
            配置字典
        """
        return {
            "base_routes": self.base_routes,
            "default_order": self.default_order,
            "conditional_routes": self.conditional_routes,
            "broadcast_patterns": self.broadcast_patterns
        }
        
    def to_json(self, indent: int = 2) -> str:
        """
        将配置转换为JSON字符串
        Args:
            indent: JSON缩进空格数
        Returns:
            JSON字符串
        """
        return json.dumps(self.to_dict(), indent=indent)
        
    @classmethod
    def from_dict(cls, data: Dict) -> 'RoutingConfig':
        """
        从字典创建配置实例
        Args:
            data: 配置字典
        Returns:
            配置实例
        """
        config = cls()
        config.base_routes = data.get("base_routes", {})
        config.default_order = data.get("default_order", [])
        config.conditional_routes = data.get("conditional_routes", [])
        config.broadcast_patterns = data.get("broadcast_patterns", [])
        return config
        
    @classmethod
    def from_json(cls, json_str: str) -> 'RoutingConfig':
        """
        从JSON字符串创建配置实例
        Args:
            json_str: JSON字符串
        Returns:
            配置实例
        """
        data = json.loads(json_str)
        return cls.from_dict(data)
        
    def apply_to_router(self, message_router: MessageRouter,
                       conditional_router: ConditionalRouter,
                       broadcast_router: BroadcastRouter) -> None:
        """
        将配置应用到路由器
        Args:
            message_router: 消息路由器实例
            conditional_router: 条件路由器实例
            broadcast_router: 广播路由器实例
        """
        # 应用基本路由规则
        message_router.base_rule.routes = self.base_routes.copy()
        message_router.base_rule.default_order = self.default_order.copy()
        
        # 应用条件路由规则
        conditional_router.clear_conditions()
        for route in self.conditional_routes:
            # 注意：这里只能应用预定义的条件，自定义条件需要手动重新添加
            if route["type"] == "content_contains":
                condition = CommonConditions.content_contains(route.get("keyword", ""))
            elif route["type"] == "message_type_is":
                condition = CommonConditions.message_type_is(route.get("msg_type", ""))
            else:
                continue
                
            conditional_router.add_condition(
                route["source"],
                condition,
                route["target"],
                route.get("description", "")
            )
            
        # 应用广播模式
        broadcast_router.clear_patterns()
        for pattern in self.broadcast_patterns:
            broadcast_router.add_broadcast_pattern(
                pattern["source"],
                pattern["targets"],
                description=pattern.get("description", "")
            )
